package com.pokerbean.housingremind.service.impl;

import com.pokerbean.housingremind.entity.HouseMsg;
import com.pokerbean.housingremind.perssist.HouseMsgMapper;
import com.pokerbean.housingremind.service.CatchService;
import com.pokerbean.housingremind.service.HousingGrabService;
import com.pokerbean.housingremind.service.SmsSendService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * created by IntelliJ IDEA
 *
 * @author: pokerbean
 * @e-mail: brutalmraz@gmail.com
 * @time: 2018/5/6 0:40
 * @desc: HousingGrabServiceImpl
 */
@Slf4j
@Service
public class HousingGrabServiceImpl implements HousingGrabService {
    @Resource
    private CatchService catchService;
    @Resource
    private HouseMsgMapper houseMsgMapper;
    @Resource
    private SmsSendService smsSendService;

    @Override
    public void grab() {
        long start = System.currentTimeMillis();
        log.info("开始爬取数据");

        Document document = catchService.getDocument("https://www.cdfangxie.com/Infor/type/typeid/36.html");
        Elements elements = document.select("[class=sp_name]");
//        System.out.println(elements);
        for (Element element : elements) {
            Element element1 = element.nextElementSibling();
            log.info("楼盘名称：{}                       拿证时间：{}",element.text(),element1.text());
        }
        long end = System.currentTimeMillis();
        log.info("爬取结束     本次爬取共消耗时间 {} ms",end-start);

        log.info("开始对比历史数据，筛选新盘信息--------------");

        for (Element projectName : elements) {
            Element sellDate = projectName.nextElementSibling();
            Map<String, String> map = new HashMap<>();
            map.put("projectName",projectName.text());
            map.put("sellDate",sellDate.text());
            HouseMsg houseMsg = houseMsgMapper.selectByNameAndDate(map);
            if (houseMsg == null) {
                HouseMsg newHouse = new HouseMsg();
                newHouse.setCreateTime(new Date());
                newHouse.setCreateUserId("成都房协网");
                newHouse.setLogicDeleteFlag(new Short("0"));
                newHouse.setId(UUID.randomUUID().toString().replaceAll("-",""));
                newHouse.setProjectName(projectName.text());
                newHouse.setSellDate(sellDate.text());
                houseMsgMapper.insertSelective(newHouse);

                //  发送短信
                log.info("正在发送短信 ：  接收人: {} ,  项目:  {}","13730871902",projectName.text());
                smsSendService.sendMsg("13730871902",sellDate.text(),projectName.text());
            }else {
                log.info("该开盘信息已是旧数据-------");
            }

        }



    }
}
